package cn.jhc.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import cn.jhc.bean.Title;
import cn.jhc.dao.DaoType;
import cn.jhc.dao.TitleDAO;
import cn.jhc.factory.DAOFactory;


/**
 * Servlet implementation class AdminAddUserServlet
 */
@WebServlet("/admin/addbook.do")
@MultipartConfig(location="${contextPath}/img", maxFileSize=1000000)
public class AdminAddBookServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private final static Pattern FILENAMEPATTERN = Pattern.compile("filename=\"(.+)\"");

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Part isbnPart = request.getPart("isbn");
		String isbn = new BufferedReader(
				new InputStreamReader(isbnPart.getInputStream()))
				.readLine();
		System.out.println("isbn=" + isbn);
		
		Part titlePart = request.getPart("titles");
		String titles = new BufferedReader(
				new InputStreamReader(titlePart.getInputStream()))
				.readLine();
		System.out.println("titles=" + titles);
		
		Part editionNumPart = request.getPart("editionNumber");
		String edition = new BufferedReader(
				new InputStreamReader(editionNumPart.getInputStream()))
				.readLine();
		System.out.println("editionNumber=" + edition);
		
		Part copyPart = request.getPart("copyright");
		String copyright = new BufferedReader(
				new InputStreamReader(copyPart.getInputStream()))
				.readLine();
		System.out.println("copyright=" + copyright);
		
		Part pubPart = request.getPart("publisherId");
		String publisherId = new BufferedReader(
				new InputStreamReader(pubPart.getInputStream()))
				.readLine();
		System.out.println("publisherId=" + publisherId);
		
		Part pricePart = request.getPart("price");
		String price = new BufferedReader(
				new InputStreamReader(pricePart.getInputStream()))
				.readLine();
		System.out.println("price=" + price);
		
		try {
			Part filePart = request.getPart("imageFile");
			String header = filePart.getHeader("Content-Disposition");
			Matcher m = FILENAMEPATTERN.matcher(header);
			String filename = "";
			if(m.find())
				filename = m.group(1);
			else {
				filename = System.currentTimeMillis() + ".png";
			}
			filePart.write(filename);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		}
	}

}
